<style>
  .layui-form-label {
    width: 90px;
  }

  .layui-input-block {
    margin-left: 120px;
  }

  #erpPurchaseRequisitions-view .layui-disabled {
    color: #393d49 !important;
    background-color: #fff;
  }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <!-- 头部操作栏 -->
      <div class="layui-form lay-header">
        <div class="toolbar">
          <div class="layui-form-item lay-query-content">
            <div class="lay-query-box">
              <div class="query-lt">
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">单据号：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="receiptsNo"
                      class="layui-input"
                      type="text"
                      placeholder="输入单据号"
                    />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">状态：</label>
                  <div class="layui-input-inline mr0">
                    <select name="status">
                      <option value="">请选择状态</option>
                      <option value="stayConfirm">待确认</option>
                      <option value="stayAudit">待审核</option>
                      <option value="success">审核成功</option>
                      <option value="fail">审核失败</option>
                      <option value="closed">已关闭</option>
                    </select>
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">物料名称：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="productName"
                      class="layui-input"
                      type="text"
                      placeholder="输入物料名称"
                    />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">制单人：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="voucherNickname"
                      class="layui-input"
                      type="text"
                      placeholder="输入制单人"
                    />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">审核人：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="auditorNickname"
                      class="layui-input"
                      type="text"
                      placeholder="输入审核人"
                    />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">时间段：</label>
                  <div class="layui-input-inline mr0">
                    <input
                      name="createTime"
                      id="pTime"
                      class="layui-input date-icon"
                      type="text"
                      placeholder="选择时间"
                      style="width: 200px"
                      readonly
                    />
                  </div>
                  <input name="startCreateTime" id="sTime" type="hidden" />
                  <input name="endCreateTime" id="eTime" type="hidden" />
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">所属部门：</label>
                  <div class="layui-input-inline mr0">
                    <input name="queryDepartmentId" type="hidden" />
                    <div
                      class="layui-input-inline mr0"
                      id="selectDepartmentQuery"
                    ></div>
                  </div>
                </div>
              </div>
              <div class="query-rt">
                <div class="layui-inline">
                  <button
                    class="layui-btn icon-btn color-green"
                    lay-filter="formSubSearchLog"
                    lay-submit
                    layui-form-keyDownSearch="true"
                  >
                    查询
                  </button>
                  <button
                    class="layui-btn icon-btn color-white"
                    lay-filter="resets"
                    lay-submit
                  >
                    重置
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="lay-btn-rows">
          <div class="lay-btn-box">
            <div class="lay-btn-lt">
              <!--<button id="purchasePlanBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>-->
              <button
                id="erpPurchaseRequisitions-btn-add"
                class="layui-btn icon-btn color-reseda"
              >
                添加
              </button>
            </div>
            <div class="lay-btn-rt"></div>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <table
        class="layui-table"
        id="erpPurchaseRequisitions-table"
        lay-filter="erpPurchaseRequisitions-table"
      ></table>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="erpPurchaseRequisitions-table-bar">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail"
    >详情</a
  >
  {{# if((d.status == "stayConfirm" || d.status == "fail")){ }}
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
  {{# } }} {{# if(d.status == "stayConfirm"){ }}
  <a class="layui-btn layui-btn layui-btn-xs" lay-event="confirm">确认</a>
  {{# } }} {{# if(d.status == "stayAudit"){ }}
  <a class="layui-btn layui-btn layui-btn-xs" lay-event="audit">审核</a>
  {{# } }} {{# if(d.status == "success"){ }} {{# if(d.enquiryStatus ==
  "inquiry"){ }}
  <a class="layui-btn layui-btn-xs" lay-event="finish">询价结束</a>
  {{# } }} {{# if(d.enquiryStatus != "finish"){ }} {{# if(d.generatorType != 2){
  }}
  <a class="layui-btn layui-btn-xs" lay-event="toProcure">生成采购单</a>
  {{# } }} {{# if(d.generatorType!= 1){ }}
  <a class="layui-btn layui-btn-xs" lay-event="generate">生成询价单</a>
  {{# } }} {{# } }}
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="close">关闭</a>
  {{# }else if(d.status != "success"){ }}
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  {{# } }}
</script>

<!-- erpPurchaseRequisitions表单弹窗 -->
<script type="text/html" id="erpPurchaseRequisitions-form">
  <form
    id="erpPurchaseRequisitions-form"
    lay-filter="erpPurchaseRequisitions-form"
    class="layui-form open-form"
  >
    <div class="open-model">
      <div class="open-auto">
        <div class="layui-row">
          <div class="layui-col-xs4">
            <label class="layui-form-label w-auto">部门：</label>
            <input name="departmentId" type="hidden" />
            <div
              class="layui-input-block"
              id="selectDepartment"
              style="margin-left: 80px;"
            ></div>
          </div>
        </div>
        <div>
          <table
            class="layui-table"
            id="erpPurchaseRequisitions-add-table"
            lay-filter="erpPurchaseRequisitions-add-table"
          ></table>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn layui-btn-primary"
          ew-event="closeDialog"
          type="button"
        >
          取消
        </button>
        <button
          class="layui-btn"
          lay-filter="erpPurchaseRequisitions-form-submit"
          lay-submit
        >
          保存
        </button>
      </div>
    </div>
  </form>
</script>

<!-- erpPurchaseRequisitions表单弹窗 -->
<script type="text/html" id="erpPurchaseRequisitions-edit">
  <form
    id="erpPurchaseRequisitions-edit"
    lay-filter="erpPurchaseRequisitions-edit"
    class="layui-form open-form"
  >
    <div class="open-model">
      <div class="open-auto">
        <input name="id" type="hidden" />
        <div class="layui-row">
          <div class="layui-col-xs4">
            <label class="layui-form-label w-auto">部门：</label>
            <input name="departmentId" type="hidden" />
            <div
              class="layui-input-block"
              id="selectDepartmentEdit"
              style="margin-left: 80px;"
            ></div>
          </div>
        </div>
        <div>
          <table
            class="layui-table"
            id="erpPurchaseRequisitions-add-table"
            lay-filter="erpPurchaseRequisitions-add-table"
          ></table>
        </div>

        <div id="audit" style="display: none;">
          <div class="layui-form-item">
            <label class="layui-form-label">审核</label>
            <div class="layui-input-block">
              <input
                name="status"
                type="radio"
                title="通过"
                value="success"
                lay-filter="getStatus"
                class="layui-input"
              />
              <input
                name="status"
                type="radio"
                title="驳回"
                value="fail"
                lay-filter="getStatus"
                class="layui-input"
              />
            </div>
          </div>
          <div class="layui-form-item" id="reason" style="display: none;">
            <label class="layui-form-label">驳回原因</label>
            <div class="layui-input-block">
              <textarea
                name="reason"
                placeholder="请输入驳回原因"
                type="text"
                maxlength="200"
                class="layui-textarea"
                style="width: 80%"
              ></textarea>
            </div>
          </div>
        </div>
        <div class="layui-form-item" id="viewAudit" style="display: none;">
          <label class="layui-form-label">驳回原因</label>
          <div class="layui-input-block">
            <textarea
              placeholder="请输入驳回原因"
              type="text"
              maxlength="200"
              class="layui-textarea"
            ></textarea>
          </div>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn layui-btn-primary"
          ew-event="closeDialog"
          type="button"
        >
          取消
        </button>
        <button
          class="layui-btn"
          lay-filter="erpPurchaseRequisitions-edit-submit"
          lay-submit
        >
          保存
        </button>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="erpPurchaseRequisitionsErpDepartmentId">
  <option value="">请选择部门</option>
  {{# layui.each(d, function(index, item){ }}
  <option value="{{item.id}}">{{item.code}}-{{item.name}}</option>
  {{# }) }}
</script>

<script type="text/html" id="erpPurchaseRequisitionsBusinessTypeId">
  <option value="">请选择业务类型</option>
  {{# layui.each(d, function(index, item){ }}
  <option value="{{item.id}}">{{item.code}}-{{item.name}}</option>
  {{# }) }}
</script>

<script type="text/html" id="erpInventoryList">
  <div class="layui-card">
    <div class="layui-card-body">
      <div class="layui-form toolbar">
        <div class="layui-form-item">
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <input
                id="erpInventoryList-code"
                class="layui-input"
                type="text"
                placeholder="输入物料编号"
              />
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <input
                id="erpInventoryList-name"
                class="layui-input"
                type="text"
                placeholder="输入物料名称"
              />
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <select id="erpInventoryList-way">
                <option value="">请选择计价方式</option>
                <option value="piece">按件</option>
                <option value="weight">按重量</option>
              </select>
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline mr0">
              <input
                name="productCategoryId"
                type="hidden"
                lay-verify="required"
              />
              <div class="layui-input-inline mr0" id="productCategoryId"></div>
            </div>
          </div>
          <div class="layui-inline">
            <button id="erpInventoryList-btn-search" class="layui-btn icon-btn">
              <i class="layui-icon">&#xe615;</i>搜索
            </button>
            <button
              id="erpInventoryList-btn-choose"
              class="layui-btn layui-btn-normal"
            >
              确认选择
            </button>
          </div>
        </div>
      </div>
      <table
        class="layui-table"
        id="erpInventoryList-table"
        lay-filter="erpInventoryList-table"
      ></table>
    </div>
  </div>
</script>

<script type="text/html" id="erpInventoryListErpInventoryClassId">
  <option value="">请选择物料分类</option>
  {{# layui.each(d, function(index, item){ }} {{# var space = ""; if(item.grade
  > 0){ for(var j = 0; j < item.grade; j++){ space += "&nbsp;&nbsp;"; } } var
  disabled = ""; if(item.isDisable == 1 || item.isParent){ disabled =
  "disabled"; } }}
  <option value="{{item.id}}" {{disabled}}>
    {{space}}{{item.code}}-{{item.name}}
  </option>
  {{# }) }}
</script>

<script type="text/html" id="quantity">
  {{# var quantity = ""; var isRequired = false; if(d.quantity != null){
  quantity = d.quantity; isRequired = true; } }}
  <div>
    <input
      name="quantity"
      placeholder="请输入数量"
      type="text"
      value="{{quantity}}"
      lay-verify="{{isRequired ? 'required|quantity' : ''}}"
      required="{{isRequired ? true : false}}"
      class="layui-input"
      maxlength="10"
      style="border: 0;height: 28px;text-align:center;"
    />
  </div>
</script>

<script type="text/html" id="rate">
  {{# var rate = ""; if(d.rate != null){ rate = d.rate; } }}
  <div>
    <input
      name="rate"
      placeholder="请输入税率"
      type="text"
      value="{{rate}}"
      lay-verify="rate"
      class="layui-input"
      maxlength="10"
      style="border: 0;height: 28px;text-align:center;"
    />
  </div>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="erpPurchaseRequisitions-add-table-bar">
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- erpPurchaseRequisitions表单弹窗 -->
<script type="text/html" id="erpPurchaseRequisitions-view">
  <form lay-filter="erpPurchaseRequisitions-view" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <input name="id" type="hidden" />
        <!--                <div class="layui-col-xs6">-->
        <!--                    <div class="layui-form-item">-->
        <!--                        <label class="layui-form-label">部门</label>-->
        <!--                        <input name="departmentId" type="hidden"/>-->
        <!--                        <div class="layui-input-block" id="selectDepartmentView"></div>-->
        <!--                    </div>-->
        <!--                </div>-->

        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">单据号</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="receiptsNo"
                class="layui-input"
                disabled
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="creatorName"
                class="layui-input"
                disabled
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">确认人</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="affirmantNickname"
                class="layui-input"
                disabled
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">审核人</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="auditorNickname"
                class="layui-input"
                disabled
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="statusDesc"
                class="layui-input"
                disabled
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label">询价状态</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="enquiryStatusDesc"
                class="layui-input"
                disabled
              />
            </div>
          </div>
        </div>
        <div>
          <table
            class="layui-table"
            id="erpPurchaseRequisitions-add-table"
            lay-filter="erpPurchaseRequisitions-add-table"
          ></table>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn layui-btn-primary"
          ew-event="closeDialog"
          type="button"
        >
          取消
        </button>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="quantity1">
  {{# var quantity = ""; var isRequired = false; if(d.quantity != null){
  quantity = d.quantity; isRequired = true; } }}
  <div>
    <input
      name="quantity"
      placeholder="请输入数量"
      type="text"
      value="{{quantity}}"
      disabled="disabled"
      lay-verify="{{isRequired ? 'required|quantity' : ''}}"
      required="{{isRequired ? true : false}}"
      class="layui-input"
      maxlength="10"
      style="border: 0;height: 28px;text-align:center;"
    />
  </div>
</script>

<script type="text/html" id="rate1">
  {{# var rate = ""; if(d.rate != null){ rate = d.rate; } }}
  <div>
    <input
      name="rate"
      placeholder="请输入税率"
      type="text"
      value="{{rate}}"
      disabled="disabled"
      lay-verify="rate"
      class="layui-input"
      maxlength="10"
      style="border: 0;height: 28px;text-align:center;"
    />
  </div>
</script>

<script type="text/html" id="erpPurchaseRequisitionsSupplierId">
  <option value="">请选择供应商</option>
  {{# layui.each(d, function(index, item){ }}
  <option value="{{item.id}}">{{item.supplierName}}</option>
  {{# }) }}
</script>

<script type="text/html" id="checkbd">
  {{# if (!d.hasGenerateOrder){ }}
  <!--这里是判断要不要显示的条件-->
  <input
    type="checkbox"
    name="siam_one"
    title=""
    lay-skin="primary"
    data-id="{{ d.id }}"
    data-code="{{ d.skuCode }}"
    data-name="{{ d.productName }}"
    data-spec="{{ d.specifications }}"
    data-unit="{{ d.mainUnitName }}"
    data-quantity="{{ d.quantity }}"
  />
  {{# }else{ }}
  <input type="checkbox" title="" lay-skin="primary" disabled />
  {{# } }}
</script>

<!--生成询价单-->
<script type="text/html" id="generatePurchaseEnquiryForm">
  <form lay-filter="generatePurchaseEnquiryForm" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto" style="padding-top: 5px;">
        <table
          class="layui-table"
          id="purchaseRequisitionsDetailTable"
          lay-filter="purchaseRequisitionsDetailTable"
        ></table>
        <!--<div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">是否过磅<span style="color:red;">*</span></label>
                        <div class="layui-input-block">
                            <select name="isWeigh" lay-filter="getIsWeigh">
                                <option value="">请选择</option>
                                <option value="1">是</option>
                                <option value="2">否</option>
                            </select>
                        </div>
                    </div>
                </div>-->
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label"
              >是否公开<span style="color:red;">*</span></label
            >
            <div class="layui-input-block">
              <select name="hasPublic" lay-filter="getHasPublic">
                <option value="true">是</option>
                <option value="false">否</option>
              </select>
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label"
              >询价结束时间<span style="color:red;">*</span></label
            >
            <div class="layui-input-block">
              <input
                name="inquiryEndTime"
                id="inquiryEndTime"
                placeholder="请选择询价结束时间"
                type="text"
                class="layui-input"
                lay-verify="required"
                required
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label"
              >交货开始时间<span style="color:red;">*</span></label
            >
            <div class="layui-input-block">
              <input
                name="deliveryStartTime"
                id="deliveryStartTime"
                placeholder="请选择交货开始时间"
                type="text"
                class="layui-input"
                lay-verify="required"
                required
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label"
              >交货截止时间<span style="color:red;">*</span></label
            >
            <div class="layui-input-block">
              <input
                name="deliveryTime"
                id="deliveryTime"
                placeholder="请选择交货时间"
                type="text"
                class="layui-input"
                lay-verify="required"
                required
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label"
              >联系人<span style="color:red;">*</span></label
            >
            <div class="layui-input-block">
              <input
                name="contactPerson"
                placeholder="请输入联系人"
                type="text"
                class="layui-input"
                lay-verify="required"
                required
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs6">
          <div class="layui-form-item">
            <label class="layui-form-label"
              >联系人电话<span style="color:red;">*</span></label
            >
            <div class="layui-input-block">
              <input
                name="contactNumber"
                placeholder="请输入联系人电话"
                type="text"
                class="layui-input"
                lay-verify="required"
                required
              />
            </div>
          </div>
        </div>
        <div class="layui-col-xs12" id="supplier" style="display: none;">
          <div class="layui-form-item">
            <label class="layui-form-label"
              >选择供应商<span style="color:red;">*</span></label
            >
            <!--<div class="layui-input-block">
                            <select name="supplierIds" xm-select="supplierIds" lay-verify="required">
                            </select>
                        </div>-->
            <input name="supplierIds" type="hidden" />
            <div class="layui-input-block" id="supplierIds"></div>
          </div>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn layui-btn-primary"
          ew-event="closeDialog"
          type="button"
        >
          取消
        </button>
        <button
          class="layui-btn"
          lay-filter="addInquiry-form-submit"
          lay-submit
        >
          生成询价单
        </button>
      </div>
    </div>
  </form>
</script>

<!-- js部分 -->
<script>
  layui.use(
    [
      "layer",
      "form",
      "table",
      "admin",
      "laytpl",
      "laydate",
      "util",
      "formSelects",
    ],
    function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      var laytpl = layui.laytpl;
      var laydate = layui.laydate;
      var util = layui.util;
      var formSelects = layui.formSelects;

      admin.initDataSelectTree(
        false,
        "user/admin/role/getTreeData",
        null,
        "selectDepartmentQuery",
        null,
        "所属部门",
        "queryDepartmentId",
        function (data) {
          var departmentIds = [];
          data.arr.forEach((item, index) => {
            departmentIds.push(item.value);
          });
          console.info(departmentIds.join(","), 899);
          $("input[name='queryDepartmentId']").val(departmentIds.join(","));
        }
      );

      form.render("select");

      //时间范围
      laydate.render({
        elem: "#pTime",
        type: "date",
        range: true,
        done: function (value, date, endDate) {
          if (value) {
            var dateValue = value.split(" - ");
            $("#sTime").val(dateValue[0] + " 00:00:00");
            $("#eTime").val(dateValue[1] + " 23:59:59");
          } else {
            $("#sTime").val("");
            $("#eTime").val("");
          }
        },
      });

      // 渲染表格
      var insTb = table.render({
        elem: "#erpPurchaseRequisitions-table",
        url:
          config.base + "enterprise/purchase/admin/purchaseRequisitions/list",
        where: {
          access_token: config.getToken().access_token,
        },
        page: true,
        cellMinWidth: 100,
        cols: [
          [
            { type: "numbers" },
            {
              field: "receiptsNo",
              align: "center",
              title: "单据号",
              width: 160,
            },
            { field: "inventoryNumber", align: "center", title: "物料数量" },
            { field: "skuNames", align: "center", title: "物料名称" },
            /*{field: 'erpBusinessTypeName',align: 'center', title: '业务类型'},*/
            { field: "statusDesc", align: "center", title: "状态" },
            // {field: 'departmentName', align: 'center', title: '所属部门'},
            { field: "creatorName", align: "center", title: "制单人" },
            { field: "affirmantNickname", title: "确认人", align: "center" },
            { field: "auditorNickname", align: "center", title: "审核人" },
            { field: "enquiryStatusDesc", align: "center", title: "询价状态" },
            { field: "createTime", sort: true, title: "创建时间", width: 170 },
            {
              align: "center",
              toolbar: "#erpPurchaseRequisitions-table-bar",
              title: "操作",
              width: 300,
            },
          ],
        ],
      });

      // 添加按钮点击事件
      $("#erpPurchaseRequisitions-btn-add").click(function () {
        // showEditModel();
        openForm("add");
      });

      function openForm(eventName, data) {
        const titleObj = {
          add: "新增请购单信息",
          edit: "修改请购单信息",
          detail: "查看请购单信息",
        };
        admin.formOpen({
          title: titleObj[eventName],
          area: ["90%", "90%"],
          offset: "50px",
          path: "components/purchase/purchaseRequisitionsForm.html",
          success: function () {
            parentData.data = data;
            parentData.eventName = eventName;
          },
        });
      }

      // 工具条点击事件
      table.on("tool(erpPurchaseRequisitions-table)", function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === "edit") {
          // 修改
          // showEditModel(data);
          admin.req(
            "enterprise/purchase/admin/purchaseRequisitionsDetail/list",
            {
              limit: 9999,
              purchaseRequisitionsId: data.id,
            },
            function (res) {
              if (200 == res.code) {
                let dataVal = { ...data };
                dataVal.list = res.data;
                openForm("edit", dataVal);
              }
            }
          );
        } else if (obj.event === "del") {
          //删除
          doDelete(obj);
        } else if (layEvent === "confirm") {
          // 确认
          doConfirm(data);
        } else if (obj.event === "audit") {
          //审核
          // showEditModel(data, layEvent);
          admin.req(
            "enterprise/purchase/admin/purchaseRequisitionsDetail/list",
            {
              limit: 9999,
              purchaseRequisitionsId: data.id,
            },
            function (res) {
              if (200 === res.code) {
                let dataVal = { ...data };
                dataVal.list = res.data;
                openForm("audit", dataVal);
              }
            }
          );
        }
        if (obj.event === "finish") {
          //询价结束
          finish(data);
        }
        if (obj.event === "toProcure") {
          //生成询价单

          // generate(data);
          // showEditModel(data, layEvent);
          admin.req(
            "enterprise/purchase/admin/purchaseRequisitionsDetail/list",
            {
              limit: 9999,
              purchaseRequisitionsId: data.id,
            },
            function (res) {
              if (200 === res.code) {
                let dataVal = { ...data };
                dataVal.list = res.data.map((v) => {
                  let obj = { ...v };
                  obj.needQuantity = obj.quantity;
                  obj.rate = obj.taxRate === "" ? "0" : obj.taxRate;
                  obj.taxPrice =
                    obj.currentCostPrice == 0 ? "0" : obj.currentCostPrice;
                  // obj.quantity = null
                  obj.quotationDetailId = obj.id;
                  if (obj.quantity && obj.taxPrice) {
                    obj.totalAmount = obj.quantity * obj.taxPrice;
                  }
                  return obj;
                });
                console.log("dataVal", dataVal);
                dataVal.purchaseQuotationId = data.id;
                admin.formOpen({
                  title: "生成采购订单",
                  area: ["90%", "90%"],
                  offset: "50px",
                  path: "components/purchase/purchaseOrderForm.html",
                  success: function () {
                    parentData.data = dataVal;
                    parentData.eventName = "add";
                    table.reload("erpPurchaseRequisitions-table");
                  },
                });
                // openForm('toProcure', dataVal)
              }
            }
          );
        }
        if (obj.event === "generate") {
          //生成询价单
          generate(data);
        } else if (obj.event === "close") {
          //关闭
          doClose(obj);
        } else if (obj.event === "detail") {
          //详情
          // showViewModel(data);
          admin.req(
            "enterprise/purchase/admin/purchaseRequisitionsDetail/list",
            {
              limit: 9999,
              purchaseRequisitionsId: data.id,
            },
            function (res) {
              if (200 == res.code) {
                let dataVal = { ...data };
                dataVal.list = res.data;
                openForm("detail", dataVal);
              }
            }
          );
        }
      });

      //显示表单弹窗
      var showEditModel = function (data, layEvent) {
        var title = data ? "更新请购单信息" : "新增请购单信息";
        var $html = data
          ? $("#erpPurchaseRequisitions-edit").html()
          : $("#erpPurchaseRequisitions-form").html();
        admin.open({
          type: 1,
          area: ["1250px", "800px"],
          title: title,
          content: $html,
          success: function () {
            var dataList = [];
            var purchaseRequisitionsDetails = []; //明细数据
            var usualData = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}];
            var codeArr = []; //物料选择集合

            admin.initDataSelectTree(
              true,
              "user/admin/role/getTreeData",
              null,
              data ? "selectDepartmentEdit" : "selectDepartment",
              data ? data.departmentId : null,
              "部门",
              "departmentId",
              null
            );

            if (data) {
              form.val("erpPurchaseRequisitions-edit", data);
              var status = data.status;
              if (status == "stayAudit" && layEvent == "audit") {
                $("#audit").show();
                form.on("radio(getStatus)", function (data) {
                  if (data.value == "fail") {
                    $("#reason").show();
                  } else {
                    $("#reason").hide();
                    $("textarea[name='reason']").val("");
                  }
                });
              } else if (status == "fail") {
                $("#viewAudit").show();
                $("#viewAudit")
                  .find("textarea")
                  .val(data.reason)
                  .attr("readonly", true);
              }
            }

            if (data) {
              //自定义验证规则
              form.verify({
                quantity: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][0-9][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
                rate: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
              });

              //获取明细数据
              admin.req(
                "enterprise/purchase/admin/purchaseRequisitionsDetail/list",
                {
                  limit: 9999,
                  purchaseRequisitionsId: data.id,
                },
                function (data) {
                  if (200 == data.code) {
                    var detail = data.data;
                    detail.reverse();
                    for (var i = 0; i < detail.length; i++) {
                      dataList.push({});
                      dataList[i].id = detail[i].id;
                      dataList[i].skuCode = detail[i].skuCode;
                      dataList[i].productName = detail[i].productName;
                      dataList[i].mainUnitName = detail[i].mainUnitName;
                      dataList[i].specifications = detail[i].specifications
                        ? detail[i].specifications
                        : "";
                      dataList[i].quantity =
                        detail[i].quantity > 0 ? detail[i].quantity : 0;
                      dataList[i].rate = detail[i].rate ? detail[i].rate : "";
                      purchaseRequisitionsDetails.push({});
                      purchaseRequisitionsDetails[i].id = detail[i].id;
                      purchaseRequisitionsDetails[i].skuCode =
                        detail[i].skuCode;
                      purchaseRequisitionsDetails[i].productName =
                        detail[i].productName;
                      purchaseRequisitionsDetails[i].mainUnitName =
                        detail[i].mainUnitName;
                      purchaseRequisitionsDetails[i].specifications = detail[i]
                        .specifications
                        ? detail[i].specifications
                        : "";
                      purchaseRequisitionsDetails[i].quantity =
                        detail[i].quantity > 0 ? detail[i].quantity : 0;
                      purchaseRequisitionsDetails[i].rate = detail[i].rate
                        ? detail[i].rate
                        : "";
                      usualData.push({});
                      usualData[i].quantity =
                        detail[i].quantity > 0 ? detail[i].quantity : 0;
                      usualData[i].rate = detail[i].rate ? detail[i].rate : "";
                      codeArr.push(detail[i].skuCode);
                    }
                    dataList.push({}, {}, {}, {}, {}, {}, {}, {}, {}, {});
                    usualData.push({}, {}, {}, {}, {}, {}, {}, {}, {}, {});
                    // 渲染表格
                    table.render({
                      elem: "#erpPurchaseRequisitions-add-table",
                      data: dataList,
                      limit: dataList.length,
                      cols: [
                        [
                          { type: "numbers" },
                          {
                            field: "productName",
                            align: "center",
                            title: "物料名称",
                            width: 160,
                            templet:
                              '<div><span class="erpInventoryId" style="display: block;cursor: pointer;" data-add="{{d.productName != null ? false : true}}">{{d.productName != null ? d.productName : "请选择物料"}}</span></div>',
                          },
                          {
                            field: "skuCode",
                            align: "center",
                            title: "物料编号",
                            width: 160,
                          },
                          {
                            field: "specifications",
                            align: "center",
                            title: "规格型号",
                            width: 150,
                          },
                          {
                            field: "mainUnitName",
                            align: "center",
                            title: "采购单位",
                            width: 150,
                          },
                          {
                            title: "数量",
                            align: "center",
                            templet: "#quantity",
                            width: 150,
                          },
                          {
                            title: "税率(%)",
                            align: "center",
                            templet: "#rate",
                            width: 150,
                          },
                          {
                            align: "center",
                            toolbar: "#erpPurchaseRequisitions-add-table-bar",
                            title: "操作",
                            width: 110,
                          },
                        ],
                      ],
                      done: function () {
                        $("input[name='quantity']").on("input", function (e) {
                          //获取input输入的值
                          var curValue = e.delegateTarget.value;
                          var curIndex = $(this).closest("tr").data("index");
                          if (purchaseRequisitionsDetails[curIndex]) {
                            purchaseRequisitionsDetails[curIndex].quantity =
                              curValue;
                          }
                          usualData[curIndex].quantity = curValue;
                          if (usualData.length - curIndex - 1 < 10) {
                            var addLength =
                              10 - (usualData.length - curIndex - 1);
                            for (var i = 0; i < addLength; i++) {
                              usualData.push({});
                            }
                          }
                        });
                        $("input[name='rate']").on("input", function (e) {
                          //获取input输入的值
                          var curValue = e.delegateTarget.value;
                          var curIndex = $(this).closest("tr").data("index");
                          if (purchaseRequisitionsDetails[curIndex]) {
                            purchaseRequisitionsDetails[curIndex].rate =
                              curValue;
                          }
                          usualData[curIndex].rate = curValue;
                          if (usualData.length - curIndex - 1 < 10) {
                            var addLength =
                              10 - (usualData.length - curIndex - 1);
                            for (var i = 0; i < addLength; i++) {
                              usualData.push({});
                            }
                          }
                        });
                        layer.closeAll("loading");
                        $(".erpInventoryId").each(function (index) {
                          $(this).click(function () {
                            var isAdd = $(this).data("add");
                            //获取物料数据
                            var erpInventoryList = layer.open({
                              type: 1,
                              title: "物料列表",
                              area: ["1100px", "700px"],
                              offset: "120px",
                              content: $("#erpInventoryList").html(),
                              success: function () {
                                form.render("select");

                                // 请求物料分类
                                let arr2tree;
                                admin.reqSync(
                                  "enterprise/product/admin/productCategory/getProductCategoryByType",
                                  { type: 0 },
                                  function (res) {
                                    for (let i = 0; i < res.data.length; i++) {
                                      res.data[i].children = [];
                                    }
                                    arr2tree = xmSelect.arr2tree(
                                      res.data,
                                      "parentId",
                                      "id",
                                      "children",
                                      -1
                                    );
                                  },
                                  "get",
                                  false
                                );

                                let smlSelectInstans = xmSelect.render({
                                  el: "#productCategoryId",
                                  model: { label: { type: "text" } },
                                  radio: true,
                                  clickClose: true,
                                  filterable: true,
                                  tree: {
                                    show: true,
                                    strict: false,
                                    expandedKeys: [-1],
                                  },
                                  tips: "请选择物料分类",
                                  prop: {
                                    name: "name",
                                    value: "id",
                                    children: "children",
                                  },
                                  data() {
                                    //填充数据
                                    return arr2tree;
                                  },
                                  on(data) {
                                    let parentId =
                                      data.arr.length > 0
                                        ? data.change[0].id
                                        : "";
                                    $("input[name='productCategoryId']").val(
                                      parentId
                                    );
                                  },
                                });

                                form.render("select");

                                var codes = "";
                                for (var i = 0; i < codeArr.length; i++) {
                                  if (i == 0) {
                                    codes = '"' + codeArr[i] + '"';
                                  } else {
                                    codes += "," + '"' + codeArr[i] + '"';
                                  }
                                }

                                // 渲染表格
                                table.render({
                                  elem: "#erpInventoryList-table",
                                  url:
                                    config.base +
                                    "enterprise/product/admin/productDetail/list",
                                  method: "GET",
                                  where: {
                                    codes: codes,
                                  },
                                  page: true,
                                  cols: [
                                    [
                                      { type: "checkbox" },
                                      {
                                        field: "skuCode",
                                        align: "center",
                                        title: "物料编号",
                                      },
                                      {
                                        field: "skuName",
                                        align: "center",
                                        title: "物料名称",
                                      },
                                      {
                                        field: "skuCode",
                                        align: "center",
                                        title: "规格型号",
                                      },
                                      {
                                        field: "mainCalWayName",
                                        align: "center",
                                        title: "计价方式",
                                      },
                                      {
                                        field: "materialNatureName",
                                        align: "center",
                                        title: "物料分类",
                                      },
                                      {
                                        field: "mainUnitName",
                                        align: "center",
                                        title: "计量单位",
                                      },
                                    ],
                                  ],
                                });

                                // 搜索按钮点击事件
                                $("#erpInventoryList-btn-search").click(
                                  function () {
                                    var name = $(
                                      "#erpInventoryList-name"
                                    ).val();
                                    var code = $(
                                      "#erpInventoryList-code"
                                    ).val();
                                    var way = $("#erpInventoryList-way").val();
                                    var categoryId = $(
                                      "input[name=productCategoryId]"
                                    ).val();
                                    table.reload("erpInventoryList-table", {
                                      page: { curr: 1 },
                                      where: {
                                        skuCode: code,
                                        skuName: name,
                                        pricingMethod: way,
                                        categoryId: categoryId,
                                      },
                                    });
                                  }
                                );

                                // 确认选择
                                $("#erpInventoryList-btn-choose").click(
                                  function () {
                                    var checkStatus = table.checkStatus(
                                      "erpInventoryList-table"
                                    ); //test即为基础参数id对应的值
                                    var dataS = checkStatus.data;
                                    for (var i = 0; i < dataS.length; i++) {
                                      dataS[i].skuCode = dataS[i].skuCode;
                                      dataS[i].productName = dataS[i].skuName;
                                      dataS[i].specifications =
                                        dataS[i].skuCode;
                                      dataS[i].mainUnitName =
                                        dataS[i].mainUnitName;
                                    }
                                    if (checkStatus.data.length == 0) {
                                      layer.msg("请选择物料", {
                                        icon: 2,
                                        time: 1000,
                                      });
                                    } else {
                                      layer.close(erpInventoryList);
                                      if (dataList.length >= 10) {
                                        dataList.splice(
                                          dataList.length - 10,
                                          10
                                        );
                                      }
                                      if (!isAdd) {
                                        dataList.splice(index, 1);
                                        usualData.splice(index, 1);
                                        codeArr.splice(index, 1);
                                        for (var i = 0; i < dataS.length; i++) {
                                          dataList.splice(
                                            index + i,
                                            0,
                                            dataS[i]
                                          );
                                          usualData.splice(index + i, 0, {});
                                          codeArr.splice(
                                            index + i,
                                            0,
                                            dataS[i].skuCode
                                          );
                                        }
                                      } else {
                                        for (var i = 0; i < dataS.length; i++) {
                                          dataList.push(dataS[i]);
                                          usualData.push({});
                                          codeArr.push(dataS[i].skuCode);
                                        }
                                      }
                                      //处理数据并存储
                                      console.log(dataList);
                                      for (
                                        var i = 0;
                                        i < dataList.length;
                                        i++
                                      ) {
                                        if (!purchaseRequisitionsDetails[i]) {
                                          purchaseRequisitionsDetails.push({});
                                        }
                                        purchaseRequisitionsDetails[i].skuCode =
                                          dataList[i].skuCode;
                                        purchaseRequisitionsDetails[
                                          i
                                        ].productName = dataList[i].productName;
                                        purchaseRequisitionsDetails[
                                          i
                                        ].mainUnitName = dataList[i]
                                          .mainUnitName
                                          ? dataList[i].mainUnitName
                                          : "";
                                        purchaseRequisitionsDetails[
                                          i
                                        ].specifications = dataList[i]
                                          .specifications
                                          ? dataList[i].specifications
                                          : "";
                                        if (usualData[i]) {
                                          dataList[i].quantity = usualData[i]
                                            .quantity
                                            ? usualData[i].quantity
                                            : "";
                                          dataList[i].rate = usualData[i].rate
                                            ? usualData[i].rate
                                            : "";
                                          purchaseRequisitionsDetails[
                                            i
                                          ].quantity = usualData[i].quantity
                                            ? usualData[i].quantity
                                            : "";
                                          purchaseRequisitionsDetails[i].rate =
                                            usualData[i].rate
                                              ? usualData[i].rate
                                              : "";
                                        } else {
                                          purchaseRequisitionsDetails[
                                            i
                                          ].quantity = "";
                                          purchaseRequisitionsDetails[i].rate =
                                            "";
                                        }
                                      }
                                      dataList.push(
                                        {},
                                        {},
                                        {},
                                        {},
                                        {},
                                        {},
                                        {},
                                        {},
                                        {},
                                        {}
                                      );
                                      if (
                                        usualData.length - dataList.length >
                                        0
                                      ) {
                                        usualData.splice(
                                          dataList.length + 1,
                                          usualData.length - dataList.length
                                        );
                                      } else {
                                        var addLength =
                                          dataList.length - usualData.length;
                                        for (var i = 0; i < addLength; i++) {
                                          usualData.push({});
                                        }
                                      }
                                      // 获取数据集合并传入请购单中
                                      table.reload(
                                        "erpPurchaseRequisitions-add-table",
                                        {
                                          data: dataList,
                                          limit: dataList.length,
                                        }
                                      );
                                    }
                                  }
                                );
                              },
                            });
                          });
                        });
                      },
                    });

                    // 工具条点击事件
                    table.on(
                      "tool(erpPurchaseRequisitions-add-table)",
                      function (obj) {
                        var data = obj.data;
                        var layEvent = obj.event;
                        if (obj.event === "del") {
                          //删除
                          doDelete(obj);
                        }
                      }
                    );

                    // 删除
                    var doDelete = function (obj) {
                      var index = $(obj.tr).data("index");
                      if (!$.isEmptyObject(obj.data)) {
                        layer.confirm(
                          "确定要删除吗？",
                          {
                            skin: "layui-layer-admin",
                          },
                          function (i) {
                            layer.close(i);
                            layer.load(2);
                            admin.req(
                              "enterprise/purchase/admin/purchaseRequisitionsDetail/" +
                                obj.data.id,
                              {},
                              function (data) {
                                layer.closeAll("loading");
                                if (data.code == 200) {
                                  layer.msg(data.msg, { icon: 1, time: 500 });
                                  dataList.splice(index, 1);
                                  purchaseRequisitionsDetails.splice(index, 1);
                                  usualData.splice(index, 1);
                                  if (codeArr.indexOf(obj.data.skuCode) >= 0) {
                                    codeArr.splice(
                                      codeArr.indexOf(obj.data.skuCode),
                                      1
                                    );
                                  }
                                  if ($.isEmptyObject(dataList[0])) {
                                    dataList = [];
                                    // 获取数据集合并传入请购单中
                                    table.reload(
                                      "erpPurchaseRequisitions-add-table",
                                      {
                                        data: [
                                          {},
                                          {},
                                          {},
                                          {},
                                          {},
                                          {},
                                          {},
                                          {},
                                          {},
                                          {},
                                        ],
                                        limit: 10,
                                      }
                                    );
                                  } else {
                                    // 获取数据集合并传入请购单中
                                    table.reload(
                                      "erpPurchaseRequisitions-add-table",
                                      {
                                        data: dataList,
                                        limit: dataList.length,
                                      }
                                    );
                                  }
                                } else {
                                  layer.msg(data.msg, { icon: 2, time: 1000 });
                                }
                              },
                              "DELETE"
                            );
                          }
                        );
                      }
                    };
                  } else {
                    layer.msg("获取明细失败", { icon: 2, time: 1000 });
                  }
                },
                "GET"
              );

              // 表单提交事件
              form.on(
                "submit(erpPurchaseRequisitions-edit-submit)",
                function (data) {
                  if (purchaseRequisitionsDetails.length > 0) {
                    data.field.purchaseRequisitionsDetails =
                      purchaseRequisitionsDetails;

                 
                    if (layEvent && layEvent == "audit") {
                      if (!$("input[name='status']:checked").val()) {
                        layer.msg("请审核", { icon: 5, time: 1000 });
                        return false;
                      }
                    }
                    console.log("data.field", data.field);
                    layer.load(2);
                    admin.req(
                      data
                        ? layEvent == "audit"
                          ? "enterprise/purchase/admin/purchaseRequisitions/audit"
                          : "enterprise/purchase/admin/purchaseRequisitions/update"
                        : "enterprise/purchase/admin/purchaseRequisitions/add",
                      JSON.stringify(data.field),
                      function (data) {
                        layer.closeAll("loading");
                        if (data.code == 200) {
                          layer.msg(data.msg, { icon: 1, time: 500 });
                          table.reload("erpPurchaseRequisitions-table");
                          layer.closeAll("page");
                        } else {
                          layer.msg(data.msg, { icon: 2, time: 1000 });
                        }
                      },
                      data ? (layEvent == "audit" ? "POST" : "PUT") : "POST",
                      false,
                      "application/json"
                    );
                  } else {
                    layer.msg("未输入发生数据，无法保存", {
                      icon: 2,
                      time: 1000,
                    });
                  }
                  return false;
                }
              );
            } else {
              //自定义验证规则
              form.verify({
                quantity: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][0-9][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
                rate: [
                  /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1})))|[ \t]*)$/,
                  "格式错误",
                ],
              });

              // 渲染表格
              table.render({
                elem: "#erpPurchaseRequisitions-add-table",
                data:
                  dataList.length > 10
                    ? dataList
                    : [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
                limit: dataList.length > 10 ? dataList.length : 10,
                cols: [
                  [
                    { type: "numbers" },
                    {
                      field: "productName",
                      align: "center",
                      title: "物料名称",
                      width: 160,
                      templet:
                        '<div><span class="erpInventoryId" style="display: block;cursor: pointer;" data-add="{{d.productName != null ? false : true}}">{{d.productName != null ? d.productName : "请选择物料"}}</span></div>',
                    },
                    {
                      field: "skuCode",
                      align: "center",
                      title: "物料编号",
                      width: 160,
                    },
                    {
                      field: "specifications",
                      align: "center",
                      title: "规格型号",
                      width: 150,
                    },
                    {
                      field: "mainUnitName",
                      align: "center",
                      title: "采购单位",
                      width: 150,
                    },
                    {
                      title: "数量",
                      align: "center",
                      templet: "#quantity",
                      width: 150,
                    },
                    {
                      title: "税率(%)",
                      align: "center",
                      templet: "#rate",
                      width: 150,
                    },
                    {
                      align: "center",
                      toolbar: "#erpPurchaseRequisitions-add-table-bar",
                      title: "操作",
                      width: 110,
                    },
                  ],
                ],
                done: function () {
                  $("input[name='quantity']").on("input", function (e) {
                    //获取input输入的值
                    var curValue = e.delegateTarget.value;
                    var curIndex = $(this).closest("tr").data("index");
                    if (purchaseRequisitionsDetails[curIndex]) {
                      purchaseRequisitionsDetails[curIndex].quantity = curValue;
                    }
                    dataList[curIndex].quantity = curValue;
                    usualData[curIndex].quantity = curValue;
                    if (usualData.length - curIndex - 1 < 10) {
                      var addLength = 10 - (usualData.length - curIndex - 1);
                      for (var i = 0; i < addLength; i++) {
                        usualData.push({});
                      }
                    }
                  });
                  $("input[name='rate']").on("input", function (e) {
                    //获取input输入的值
                    var curValue = e.delegateTarget.value;
                    var curIndex = $(this).closest("tr").data("index");
                    if (purchaseRequisitionsDetails[curIndex]) {
                      purchaseRequisitionsDetails[curIndex].rate = curValue;
                    }
                    usualData[curIndex].rate = curValue;
                    if (usualData.length - curIndex - 1 < 10) {
                      var addLength = 10 - (usualData.length - curIndex - 1);
                      for (var i = 0; i < addLength; i++) {
                        usualData.push({});
                      }
                    }
                  });
                  layer.closeAll("loading");
                  $(".erpInventoryId").each(function (index) {
                    $(this).click(function () {
                      var isAdd = $(this).data("add");
                      //获取物料数据
                      var erpInventoryList = layer.open({
                        type: 1,
                        title: "物料SKU列表",
                        area: ["1100px", "700px"],
                        offset: "120px",
                        content: $("#erpInventoryList").html(),
                        success: function () {
                          form.render("select");

                          // 请求物料分类
                          admin.initDataSelectTree(
                            true,
                            "enterprise/product/admin/productType/getTreeData",
                            null,
                            "productCategoryId",
                            null,
                            "物料分类",
                            "productCategoryId",
                            null
                          );

                          var codes = "";
                          for (var i = 0; i < codeArr.length; i++) {
                            if (i == 0) {
                              codes = '"' + codeArr[i] + '"';
                            } else {
                              codes += "," + '"' + codeArr[i] + '"';
                            }
                          }

                          // 渲染表格
                          table.render({
                            elem: "#erpInventoryList-table",
                            url:
                              config.base +
                              "enterprise/product/admin/productDetail/list",
                            method: "GET",
                            where: {
                              codes: codes,
                            },
                            page: true,
                            cols: [
                              [
                                { type: "checkbox" },
                                {
                                  field: "skuCode",
                                  align: "center",
                                  title: "物料编号",
                                },
                                {
                                  field: "skuName",
                                  align: "center",
                                  title: "物料名称",
                                },
                                {
                                  field: "skuCode",
                                  align: "center",
                                  title: "规格型号",
                                },
                                {
                                  field: "mainCalWayName",
                                  align: "center",
                                  title: "计价方式",
                                },
                                {
                                  field: "materialNatureName",
                                  align: "center",
                                  title: "物料分类",
                                },
                                {
                                  field: "mainUnitName",
                                  align: "center",
                                  title: "计量单位",
                                },
                              ],
                            ],
                          });

                          // 搜索按钮点击事件
                          $("#erpInventoryList-btn-search").click(function () {
                            var name = $("#erpInventoryList-name").val();
                            var code = $("#erpInventoryList-code").val();
                            var way = $("#erpInventoryList-way").val();
                            var categoryId = $(
                              "input[name=productCategoryId]"
                            ).val();
                            table.reload("erpInventoryList-table", {
                              page: { curr: 1 },
                              where: {
                                skuCode: code,
                                skuName: name,
                                pricingMethod: way,
                                categoryId: categoryId,
                              },
                            });
                          });

                          // 确认选择
                          $("#erpInventoryList-btn-choose").click(function () {
                            var checkStatus = table.checkStatus(
                              "erpInventoryList-table"
                            ); //test即为基础参数id对应的值
                            var dataS = checkStatus.data;
                            for (var i = 0; i < dataS.length; i++) {
                              dataS[i].skuCode = dataS[i].skuCode;
                              dataS[i].productName = dataS[i].skuName;
                              dataS[i].specifications = dataS[i].skuCode;
                              dataS[i].mainUnitName = dataS[i].mainUnitName;
                            }
                            if (checkStatus.data.length == 0) {
                              layer.msg("请选择物料", { icon: 2, time: 1000 });
                            } else {
                              layer.close(erpInventoryList);
                              if (dataList.length >= 10) {
                                dataList.splice(dataList.length - 10, 10);
                              }
                              if (!isAdd) {
                                dataList.splice(index, 1);
                                usualData.splice(index, 1);
                                codeArr.splice(index, 1);
                                for (var i = 0; i < dataS.length; i++) {
                                  dataList.splice(index + i, 0, dataS[i]);
                                  usualData.splice(index + i, 0, {});
                                  codeArr.splice(
                                    index + i,
                                    0,
                                    dataS[i].skuCode
                                  );
                                }
                              } else {
                                for (var i = 0; i < dataS.length; i++) {
                                  dataList.push(dataS[i]);
                                  usualData.push({});
                                  codeArr.push(dataS[i].skuCode);
                                }
                              }
                              //处理数据并存储
                              for (var i = 0; i < dataList.length; i++) {
                                if (!purchaseRequisitionsDetails[i]) {
                                  purchaseRequisitionsDetails.push({});
                                }
                                purchaseRequisitionsDetails[i].skuCode =
                                  dataList[i].skuCode;
                                purchaseRequisitionsDetails[i].productName =
                                  dataList[i].productName;
                                purchaseRequisitionsDetails[i].mainUnitName =
                                  dataList[i].mainUnitName
                                    ? dataList[i].mainUnitName
                                    : "";
                                purchaseRequisitionsDetails[i].specifications =
                                  dataList[i].specifications
                                    ? dataList[i].specifications
                                    : "";
                                if (usualData[i]) {
                                  dataList[i].quantity = usualData[i].quantity
                                    ? usualData[i].quantity
                                    : "";
                                  dataList[i].rate = usualData[i].rate
                                    ? usualData[i].rate
                                    : "";
                                  purchaseRequisitionsDetails[i].quantity =
                                    usualData[i].quantity
                                      ? usualData[i].quantity
                                      : "";
                                  purchaseRequisitionsDetails[i].rate =
                                    usualData[i].rate ? usualData[i].rate : "";
                                } else {
                                  purchaseRequisitionsDetails[i].quantity = "";
                                  purchaseRequisitionsDetails[i].rate = "";
                                }
                              }
                              dataList.push(
                                {},
                                {},
                                {},
                                {},
                                {},
                                {},
                                {},
                                {},
                                {},
                                {}
                              );
                              if (usualData.length - dataList.length > 0) {
                                usualData.splice(
                                  dataList.length + 1,
                                  usualData.length - dataList.length
                                );
                              } else {
                                var addLength =
                                  dataList.length - usualData.length;
                                for (var i = 0; i < addLength; i++) {
                                  usualData.push({});
                                }
                              }
                              // 获取数据集合并传入请购单中
                              table.reload(
                                "erpPurchaseRequisitions-add-table",
                                {
                                  data: dataList,
                                  limit: dataList.length,
                                }
                              );
                            }
                          });
                        },
                      });
                    });
                  });
                },
              });

              // 工具条点击事件
              table.on(
                "tool(erpPurchaseRequisitions-add-table)",
                function (obj) {
                  var data = obj.data;
                  var layEvent = obj.event;
                  if (obj.event === "del") {
                    //删除
                    doDelete(obj);
                  }
                }
              );

              // 删除
              var doDelete = function (obj) {
                var index = $(obj.tr).data("index");
                if (!$.isEmptyObject(obj.data)) {
                  layer.confirm(
                    "确定要删除吗？",
                    {
                      skin: "layui-layer-admin",
                    },
                    function (i) {
                      layer.close(i);
                      //obj.del();
                      dataList.splice(index, 1);
                      purchaseRequisitionsDetails.splice(index, 1);
                      usualData.splice(index, 1);
                      if (codeArr.indexOf(obj.data.skuCode) >= 0) {
                        codeArr.splice(codeArr.indexOf(obj.data.skuCode), 1);
                      }
                      if ($.isEmptyObject(dataList[0])) {
                        dataList = [];
                        // 获取数据集合并传入请购单中
                        table.reload("erpPurchaseRequisitions-add-table", {
                          data: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
                          limit: 10,
                        });
                      } else {
                        // 获取数据集合并传入请购单中
                        table.reload("erpPurchaseRequisitions-add-table", {
                          data: dataList,
                          limit: dataList.length,
                        });
                      }
                    }
                  );
                }
              };

              // 表单提交事件
              form.on(
                "submit(erpPurchaseRequisitions-form-submit)",
                function (data) {
                  if (purchaseRequisitionsDetails.length > 0) {
                    data.field.purchaseRequisitionsDetails =
                      purchaseRequisitionsDetails;
                    layer.load(2);
                    admin.req(
                      "enterprise/purchase/admin/purchaseRequisitions/add",
                      JSON.stringify(data.field),
                      function (data) {
                        layer.closeAll("loading");
                        if (data.code == 200) {
                          layer.msg(data.msg, { icon: 1, time: 500 });
                          table.reload("erpPurchaseRequisitions-table");
                          layer.closeAll("page");
                        } else {
                          layer.msg(data.msg, { icon: 2, time: 1000 });
                        }
                      },
                      "POST",
                      false,
                      "application/json"
                    );
                  } else {
                    layer.msg("未输入发生数据，无法保存", {
                      icon: 2,
                      time: 1000,
                    });
                  }
                  return false;
                }
              );
            }
          },
        });
      };

      //详情
      var showViewModel = function (data) {
        admin.open({
          type: 1,
          area: ["1200px", "800px"],
          title: "请购单详情",
          content: $("#erpPurchaseRequisitions-view").html(),
          success: function () {
            form.render();

            admin.initDataSelectTree(
              true,
              "user/admin/role/getTreeData",
              null,
              "selectDepartmentView",
              data.departmentId,
              "部门",
              "departmentId",
              null
            );

            form.val("erpPurchaseRequisitions-view", data);

            //询价结束时间
            laydate.render({
              elem: "#inquiryEndTime", //指定元素
              type: "datetime",
            });

            //交货开始时间
            laydate.render({
              elem: "#deliveryStartTime", //指定元素
              type: "datetime",
            });

            //交货截止时间
            laydate.render({
              elem: "#deliveryTime", //指定元素
              type: "datetime",
            });

            var status = data.status; //审核状态
            if (status == "success" || status == "fail") {
              $("#audit").show();
              $("input[name='status']").each(function () {
                if ($(this).val() == status) {
                  $(this).attr("checked", true);
                }
              });
              if (status == "fail") {
                $("#reason").show();
              }
            }

            getErpPurchaseRequisitionsDetail();

            function getErpPurchaseRequisitionsDetail(isWeigh) {
              dataList = [];
              //获取明细数据
              admin.req(
                "enterprise/purchase/admin/purchaseRequisitionsDetail/list",
                {
                  purchaseRequisitionsId: data.id,
                  isWeigh: isWeigh,
                },
                function (d) {
                  if (200 == d.code) {
                    var detail = d.data;
                    detail.reverse();
                    for (var i = 0; i < detail.length; i++) {
                      dataList.push({});
                      dataList[i].id = detail[i].id;
                      dataList[i].isGenerateOrder = detail[i].isGenerateOrder;
                      dataList[i].skuCode = detail[i].skuCode;
                      dataList[i].productName = detail[i].productName;
                      dataList[i].mainUnitName = detail[i].mainUnitName;
                      dataList[i].specifications = detail[i].specifications
                        ? detail[i].specifications
                        : "";
                      dataList[i].quantity = detail[i].quantity
                        ? detail[i].quantity
                        : "";
                      dataList[i].rate = detail[i].rate ? detail[i].rate : "";
                    }
                    // 渲染表格
                    table.render({
                      elem: "#erpPurchaseRequisitions-add-table",
                      data: dataList,
                      limit: dataList.length,
                      cols: [
                        [
                          { type: "numbers" },
                          {
                            field: "productName",
                            align: "center",
                            title: "物料名称",
                            width: 180,
                            templet:
                              '<div><span class="erpInventoryId" style="display: block;cursor: pointer;" data-add="{{d.productName != null ? false : true}}">{{d.productName != null ? d.productName : "请选择物料"}}</span></div>',
                          },
                          {
                            field: "skuCode",
                            align: "center",
                            title: "物料编号",
                            width: 180,
                          },
                          {
                            field: "specifications",
                            align: "center",
                            title: "规格型号",
                            width: 180,
                          },
                          {
                            field: "mainUnitName",
                            align: "center",
                            title: "采购单位",
                            width: 150,
                          },
                          {
                            title: "数量",
                            align: "center",
                            templet: "#quantity1",
                            width: 180,
                          },
                          {
                            title: "税率(%)",
                            align: "center",
                            templet: "#rate1",
                            width: 170,
                          },
                        ],
                      ],
                      done: function () {
                        layer.closeAll("loading");
                      },
                    });
                  } else {
                    layer.msg("获取明细失败", { icon: 2, time: 1000 });
                  }
                },
                "GET",
                true
              );
            }
          },
        });
      };

      // 删除
      var doDelete = function (obj) {
        layer.confirm(
          "确定要删除吗？",
          {
            skin: "layui-layer-admin",
          },
          function (i) {
            layer.close(i);
            layer.load(2);
            admin.req(
              "enterprise/purchase/admin/purchaseRequisitions/" + obj.data.id,
              {},
              function (data) {
                layer.closeAll("loading");
                if (data.code == 200) {
                  layer.msg(data.msg, { icon: 1, time: 500 });
                  obj.del();
                } else {
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                }
              },
              "DELETE"
            );
          }
        );
      };

      //确认
      var doConfirm = function (data) {
        layer.confirm(
          "要确认吗？",
          {
            skin: "layui-layer-admin",
          },
          function (i) {
            layer.close(i);
            layer.load(2);
            admin.req(
              "enterprise/purchase/admin/purchaseRequisitions/confirm",
              { id: data.id },
              function (data) {
                layer.closeAll("loading");
                if (data.code == 200) {
                  layer.msg(data.msg, { icon: 1, time: 500 });
                  /* table.reload('erpPurchaseRequisitions-table', {});*/
                  table.reload("erpPurchaseRequisitions-table");
                } else {
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                }
              },
              "GET"
            );
          }
        );
      };

      //询价结束
      var finish = function (data) {
        layer.confirm(
          "确定要询价结束吗？",
          {
            skin: "layui-layer-admin",
          },
          function (i) {
            layer.close(i);
            layer.load(2);
            admin.req(
              "enterprise/purchase/admin/purchaseRequisitions/finish",
              { id: data.id },
              function (data) {
                layer.closeAll("loading");
                if (data.code == 200) {
                  layer.msg(data.msg, { icon: 1, time: 500 });
                  table.reload("erpPurchaseRequisitions-table", {});
                } else {
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                }
              },
              "GET"
            );
          }
        );
      };

      // 生成询价单
      function generate(data) {
        var purchaseRequisitionsId = data.id;
        admin.open({
          type: 1,
          area: ["1200px", "800px"],
          title: "生成询价单",
          content: $("#generatePurchaseEnquiryForm").html(),
          success: function () {
            form.render();

            //询价结束时间
            laydate.render({
              elem: "#inquiryEndTime", //指定元素
              type: "datetime",
            });

            //交货开始时间
            laydate.render({
              elem: "#deliveryStartTime", //指定元素
              type: "datetime",
            });

            //交货截止时间
            laydate.render({
              elem: "#deliveryTime", //指定元素
              type: "datetime",
            });

            var status = data.status; //审核状态
            var enquiryStatus = data.enquiryStatus; //询价状态
            if (status == "success" || status == "fail") {
              $("#audit").show();
              $("input[name='status']").each(function () {
                if ($(this).val() == status) {
                  $(this).attr("checked", true);
                }
              });
              if (status == "fail") {
                $("#reason").show();
              }
              if (enquiryStatus != "finish") {
                // 询价状态不等于询价结束
                $("#addInquiry").show();
                //全选
                form.on("checkbox(siam_all)", function () {
                  var status = $(this).prop("checked");
                  $.each($("input[name=siam_one]"), function (i, value) {
                    $(this).prop("checked", status);
                  });
                  form.render();
                });
              }
            }

            // 选择是否过磅
            /*form.on("select(getIsWeigh)", function (data) {
                        // 过滤物料
                        getErpPurchaseRequisitionsDetail(data.value);
                    })*/

            // 获取是否公开
            form.on("select(getHasPublic)", function (data) {
              // 查询询价单
              if (data.value == "false") {
                $("#supplier").show();
              } else {
                $("#supplier").hide();
                var sub = $(".icon-qingkong");
                sub.click();
              }
            });

            // 获取供应商
            admin.req(
              "enterprise/purchase/admin/supplierInfoPass/list",
              { limit: 99999 },
              function (data) {
                if (200 == data.code) {
                  // 渲染多选下拉框
                  var supplierSelectData = new Array();
                  for (var i = 0; i < data.data.length; i++) {
                    supplierSelectData.push({
                      name: data.data[i].corporateName,
                      value: data.data[i].id,
                    });
                  }
                  xmSelect.render({
                    el: "#supplierIds",
                    data() {
                      return supplierSelectData;
                    },
                    on: function (data) {
                      console.log(data);
                      if (data.arr.length > 0) {
                        var supplierIds = "";
                        for (var i = 0; i < data.arr.length; i++) {
                          if (supplierIds == "") {
                            supplierIds = data.arr[i].value;
                          } else {
                            supplierIds += "," + data.arr[i].value;
                          }
                        }
                        $("input[name='supplierIds']").val(supplierIds);
                      }
                    },
                  });
                } else {
                  layer.msg("获取供应商失败", { icon: 2, time: 1000 });
                }
              },
              "GET"
            );

            getErpPurchaseRequisitionsDetail();

            function getErpPurchaseRequisitionsDetail(isWeigh) {
              dataList = [];
              //获取明细数据
              admin.req(
                "enterprise/purchase/admin/purchaseRequisitionsDetail/list",
                {
                  purchaseRequisitionsId: data.id,
                  isWeigh: isWeigh,
                },
                function (d) {
                  if (200 == d.code) {
                    var detail = d.data;
                    detail.reverse();
                    for (var i = 0; i < detail.length; i++) {
                      dataList.push({});
                      dataList[i].id = detail[i].id;
                      dataList[i].hasGenerateOrder = detail[i].hasGenerateOrder;
                      dataList[i].skuCode = detail[i].skuCode;
                      dataList[i].productName = detail[i].productName;
                      dataList[i].mainUnitName = detail[i].mainUnitName;
                      dataList[i].specifications = detail[i].specifications
                        ? detail[i].specifications
                        : "";
                      dataList[i].quantity = detail[i].quantity
                        ? detail[i].quantity
                        : "";
                      dataList[i].rate = detail[i].rate ? detail[i].rate : "";
                    }
                    // 渲染表格
                    table.render({
                      elem: "#purchaseRequisitionsDetailTable",
                      data: dataList,
                      limit: dataList.length,
                      cols: [
                        [
                          {
                            templet: "#checkbd",
                            title:
                              "<input type='checkbox' name='siam_all' title='' lay-skin='primary' lay-filter='siam_all' /> ",
                            width: 48,
                          },
                          {
                            field: "productName",
                            align: "center",
                            title: "物料名称",
                            width: 180,
                            templet:
                              '<div><span class="erpInventoryId" style="display: block;cursor: pointer;" data-add="{{d.productName != null ? false : true}}">{{d.productName != null ? d.productName : "请选择物料"}}</span></div>',
                          },
                          {
                            field: "skuCode",
                            align: "center",
                            title: "物料编号",
                            width: 180,
                          },
                          {
                            field: "specifications",
                            align: "center",
                            title: "规格型号",
                            width: 180,
                          },
                          {
                            field: "mainUnitName",
                            align: "center",
                            title: "采购单位",
                            width: 150,
                          },
                          {
                            field: "quantity",
                            title: "数量",
                            align: "center",
                            width: 180,
                          },
                          {
                            field: "rate",
                            title: "税率(%)",
                            align: "center",
                            width: 170,
                          },
                        ],
                      ],
                      done: function () {
                        layer.closeAll("loading");
                      },
                    });
                  } else {
                    layer.msg("获取明细失败", { icon: 2, time: 1000 });
                  }
                },
                "GET",
                true
              );
            }

            // 添加询价
            // 表单提交事件
            form.on("submit(addInquiry-form-submit)", function (data) {
              var checkStatus = [];
              $.each($("input[name=siam_one]:checked"), function () {
                var json = {};
                json.purchaseRequisitionsDetailId = $(this).attr("data-id"); // 如果需要获取其他的值 需要在模板中把值放到属性中 然后这里就可以拿到了
                json.skuCode = $(this).attr("data-code");
                json.productName = $(this).attr("data-name");
                json.specifications = $(this).attr("data-spec");
                json.mainUnitName = $(this).attr("data-unit");
                json.quantity = $(this).attr("data-quantity");
                checkStatus.push(json);
              });
              data.field.purchaseRequisitionsId = purchaseRequisitionsId;
              if (data.field.hasPublic == "false") {
                if (data.field.supplierIds == "") {
                  layer.msg("请选择供应商", { icon: 2, time: 1000 });
                  return false;
                }
              } else {
                data.field.supplierIds = null;
              }
              if (checkStatus.length > 0) {
                data.field.purchaseEnquiryDetails = checkStatus;
                layer.load(2);
                admin.req(
                  "enterprise/purchase/admin/purchaseEnquiry/add",
                  JSON.stringify(data.field),
                  function (data) {
                    layer.closeAll("loading");
                    if (data.code == 200) {
                      layer.msg(data.msg, { icon: 1, time: 500 });
                      table.reload("erpPurchaseRequisitions-table", {});
                      layer.closeAll("page");
                    } else {
                      layer.msg(data.msg, { icon: 2, time: 1000 });
                    }
                  },
                  "POST",
                  false,
                  "application/json"
                );
              } else {
                layer.msg("请选择物料", { icon: 2, time: 1000 });
              }
              return false;
            });
          },
        });
      }

      // 关闭
      var doClose = function (obj) {
        layer.confirm(
          "确定要关闭吗？",
          {
            skin: "layui-layer-admin",
          },
          function (i) {
            layer.close(i);
            layer.load(2);
            admin.req(
              "enterprise/purchase/admin/purchaseRequisitions/close",
              { id: obj.data.id },
              function (data) {
                layer.closeAll("loading");
                if (data.code == 200) {
                  layer.msg(data.msg, { icon: 1, time: 500 });
                  table.reload("erpPurchaseRequisitions-table", {});
                } else {
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                }
              },
              "GET"
            );
          }
        );
      };

      // 搜索
      form.on("submit(formSubSearchLog)", function (data) {
        insTb.reload({ where: data.field, page: { curr: 1 } }, "data");
      });

      // 重置搜索
      form.on("submit(resets)", function (data) {
        insTb.reload(
          { where: admin.resetSearch(data.field), page: { curr: 1 } },
          "data"
        );
      });

      // 导出excel
      $("#erpPurchaseRequisitionsBtnExport").click(function () {
        var checkRows = table.checkStatus("erpPurchaseRequisitions-table");
        if (checkRows.data.length == 0) {
          layer.msg("请选择要导出的数据", { icon: 2 });
        } else {
          table.exportFile(insTb.config.id, checkRows.data, "xls");
        }
      });
    }
  );
</script>
